import React, { PureComponent } from "react";
import store from "../store/index";
import { addAction, minusAction } from "../store/actionCreators";

export class Home extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      counter: store.getState().counter,
    };
  }

  unsubscribe = null;

  componentWillUnmount() {
    if (this.unsubscribe) {
      this.unsubscribe();
    }
  }

  componentDidMount() {
    this.unsubscribe = store.subscribe(() => {
      this.setState({
        counter: store.getState().counter,
      });
    });
  }

  handAdd = (num) => {
    store.dispatch(addAction(num));
  };
  handMinus = (num) => {
    store.dispatch(minusAction(num));
  };

  render() {
    const { counter } = this.state;
    return (
      <div>
        <h3>Home counter : {counter}</h3>
        <div className="btn-group">
          <button onClick={() => this.handAdd(1)}>+1</button>
          <button onClick={() => this.handAdd(5)}>+5</button>
          <button onClick={() => this.handMinus(3)}>-3</button>
        </div>
      </div>
    );
  }
}

export default Home;
